package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bwie.handler.CreateMyException;
import com.bwie.pojo.User;
import com.bwie.service.Token;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

import static com.bwie.controller.Controller.code;

@Service
public class TokenImpl implements Token {

    @Autowired
    TbUserServiceImpl tbUserService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public String gettoken(User user) {
        if (user.getUserName().equals("")){
            throw new CreateMyException(222,"用户名不能为空");
        }
        if (user.getUserPass().equals("")){
            throw new CreateMyException(222,"密码不能为空");
        }
        User one = tbUserService.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getUserName, user.getUserName())
                .eq(User::getUserPass, user.getUserPass())
        );
        if (one==null){
            throw new CreateMyException(222,"账号或密码错误");
        }
        long l = System.currentTimeMillis();
        long l1 = l + (86400000L * 7);
        long l2 = l + (1800000L);
        String userIdLO = Jwts.builder().signWith(SignatureAlgorithm.HS256, code)
                .claim("userId", one.getUserId())
                .setExpiration(new Date(l1))//设置该token7天后过期
                .compact();
        String userIdLI = Jwts.builder().signWith(SignatureAlgorithm.HS256, code)
                .claim("userId", one.getUserId())
                .setExpiration(new Date(l2))
                .compact();
        stringRedisTemplate.opsForValue().set(userIdLI,userIdLO);
        return userIdLI;
    }

    @Override
    public String checktoken(User user) {
        String token = user.getToken();
        Claims body = null;
        try {
            body = Jwts.parser().setSigningKey(code).parseClaimsJws(token).getBody();
        }catch (Exception e){
            throw new CreateMyException(444,"token过期");
        }
        String userId = body.get("userId").toString();

        long l = System.currentTimeMillis();
        long l1 = l + (1800000L);
        String userId1 = Jwts.builder().setExpiration(new Date(l1))
                .claim("userId", userId)
                .compact();

        //获取长期token
        String tokanLO = stringRedisTemplate.opsForValue().get(token);

        //删除老token
        stringRedisTemplate.delete(token);

        //保存新token
        stringRedisTemplate.opsForValue().set(userId1,tokanLO);

        return userId1;
    }
}
